{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "Common code used in multiple places in this\n",
    "chapter.\n",
    "\"\"\"\n",
    "import torch\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pca(X):\n",
    "    \"\"\"\n",
    "    X: Matrix such that rows correspond to data \n",
    "       points and columns correspond to the\n",
    "       features.\n",
    "    Returns principal values, principal\n",
    "    components\n",
    "    \"\"\"\n",
    "    assert len(X.shape) == 2\n",
    "    #We use X.T as each column is a variable\n",
    "    covariance_matrix = torch.cov(X.T) \n",
    "    l, e = torch.linalg.eig(covariance_matrix)\n",
    "    return l, e"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def draw_line(direction_vector,\n",
    "              min_x=0, max_x=10,\n",
    "              color='magenta'):\n",
    "    \"\"\"\n",
    "    Draw a line along the direction vector\n",
    "    from (min_x to max_x)\n",
    "    \"\"\"\n",
    "    # fill up the array such that the \n",
    "    # the 0th column (line[:, 0]) contains x values\n",
    "    # and the 1th column (line[:, 1]) contains y\n",
    "    # values.\n",
    "    line = np.array([direction_vector * v for v in \n",
    "                     np.linspace(min_x, max_x, 100)])\n",
    "    plt.plot(line[:, 0], line[:, 1], color=color)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
